#include "ChooseIslandState.h"
#include "ResMgr.h"
#include "Texture.h"
#include "AnimationSprite.h"
#include "Animation.h"
#include "Button.h"
#include "Utils.h"
#include "GameUtils.h"
#include "StateMgr.h"
#include "ChooseLevelState.h"
#include "PlayState.h"
#include "Box.h"
#include "GameCommonInfo.h"

ChooseIslandState::ChooseIslandState()
{

}

void ChooseIslandState::Init()
{
	ResMgr::GetInstance()->LoadChooseIslandRes();
	background = ResMgr::GetInstance()->GetTexture(TID_MAIN_MENU_BACK);
	aniSprite = new AnimationSprite();
	Animation* ani = new Animation(0);
	ani->GenerateAuto(ResMgr::GetInstance()->GetTexture(TID_ISLANDS_BUTTON),
					  W_ISLAND_BUTTON_SPRITE, H_ISLAND_BUTTON_SPRITE, 2, 0, 11, 0);
	aniSprite->AddAnimation(ani);

	Button* button;

	for(int i = 0; i < NUM_ISLAND; i++)
	{
		button = new Button(X_BUTTON_ISLAND + DX_BUTTON*(i%3), 
			Y_BUTTON_ISLAND + DY_BUTTON*(i/3), 
			W_BUTTON, H_BUTTON);
		button->SetImageForTouchUp(aniSprite, 0, 2*i);
		button->SetImageForTouchDown(aniSprite, 0, 2*i+1);
		button->SetID(i);
		buttons.push_back(button);
	}

	GameCommonInfo* gci = GameCommonInfo::GetInstance();
	if(gci->GetBoxes()->size() == 0)
		Box::LoadBoxes(gci->GetBoxes());
}

void ChooseIslandState::Render()
{
	background->Render(0, 0);
	for(int i = 0; i < buttons.size(); i++)
		buttons[i]->Render();
}

void ChooseIslandState::TouchDown(int x, int y)
{
	for(int i = 0; i < NUM_ISLAND; i++)
	{

		if(IsPointInRect(x, y, buttons[i]->GetRect()))
		{
			buttons[i]->TouchDown();
			OnButtonClick(buttons[i], BTE_TOUCH_DOWN);
		}
	}
}

void ChooseIslandState::TouchUp(int x, int y)
{
	for(int i = 0; i < NUM_ISLAND; i++)
	{
		
		if(IsPointInRect(x, y, buttons[i]->GetRect()))
		{
			buttons[i]->TouchUp();
			OnButtonClick(buttons[i], BTE_TOUCH_UP);
		}
	}
}

void ChooseIslandState::OnButtonClick(Button* sender, int e)
{
	if(e == BTE_TOUCH_UP)
	{
		GameCommonInfo::GetInstance()->SetCurBox(sender->GetID());
		StateMgr::GetInstance()->SwitchState(new ChooseLevelState());
	}
	
}
ChooseIslandState::~ChooseIslandState()
{
	for(int i = 0; i < buttons.size(); i++)
	{
		DELETE_SAFELY(buttons[i]);
	}
	buttons.clear();

	DELETE_SAFELY(aniSprite);
	ResMgr::GetInstance()->UnloadChooseIslandRes();
}